// 要使用一个模块 应该先把这个模块引入了
const gulp = require('gulp'),
    htmlmin = require('gulp-htmlmin'),
    gulpsass = require('gulp-sass'),
    cleanCss = require('gulp-clean-css'),
    del = require('del'),
    babel = require('gulp-babel'),
    uglify = require('gulp-uglify'),
    connect = require('gulp-connect'),
    {createProxyMiddleware}=require('http-proxy-middleware')

// 定制 删除 dist 目录 任务
const delDist = () => del('dist')

// 定制 html 任务(函数)
const html = () => {
    // src 目录下的所有文件夹里面所有的 以 .html 结尾的文件
    return gulp.src('./src/**/*.html')
        .pipe(htmlmin({
            removeComments: true, // 清除HTML注释
            collapseWhitespace: true, // 压缩HTML
            collapseBooleanAttributes: true, // 省略布尔属性的值 <input checked="true"/> ==> <input checked />
            removeEmptyAttributes: true, // 删除所有空格作属性值 <input id="" /> ==> <input />
            removeScriptTypeAttributes: false, // 删除<script>的type="text/javascript"
            removeStyleLinkTypeAttributes: false, // 删除<style>和<link>的type="text/css"
            minifyJS: true, // 压缩页面JS
            minifyCSS: true // 压缩页面CSS 
        }))
        .pipe(gulp.dest('./dist'))
        .pipe(connect.reload())
}

// 定制 sass 任务
const sass = () => {
    //  读取文件
    return gulp.src('./src/sass/*.scss')
            .pipe(gulpsass())
            .pipe(cleanCss())
            .pipe(gulp.dest('./dist/css'))
            .pipe(connect.reload())
}


// 定制 js 任务
const js = () => {
    return gulp.src('./src/js/*.js')
           .pipe(babel({
            presets: ['@babel/env']        // ES6 转为 ES5
          }))       
           .pipe(uglify())   // 压缩 js
           .pipe(gulp.dest('./dist/js'))
           .pipe(connect.reload())
}

const imgs = () => gulp.src('./src/images/**/*.*').pipe(gulp.dest('./dist/images'))
const lib = () => gulp.src('./src/lib/**/*.*').pipe(gulp.dest('./dist/lib'))
const ico = () => gulp.src('./src/*.ico').pipe(gulp.dest('./dist'))

const watch = () => {
    gulp.watch('./src/**/*.html',html)
    gulp.watch('./src/sass/*.scss',sass)
    gulp.watch('./src/js/*.js',js)
}

// 开启一个服务器
const server = () => {
    connect.server({
        port:2101,
        root:'./dist',
        livereload:true,
        middleware(){
            return[
                createProxyMiddleware('duitang',{
                target: 'https://www.duitang.com/napi/blog/list/by_album/',
                changeOrigin: true,
                pathRewrite: {
                            '^/api':''
                        }
                })
            ]
        }
    })
}


// 但是我们还没有运行
// series 同步执行任务
module.exports.default = gulp.series(delDist,gulp.parallel(html,sass,js,imgs,lib,ico,server,watch)) 